﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using ExcelCOM = Microsoft.Office.Interop.Excel;

namespace LanAnh
{
    public partial class frmKhachHang : Office2007Form
    {
        public frmKhachHang()
        {
            InitializeComponent();
        }
        public frmKhachHang(string phanquyen)
        {            
            Status.Init();
            InitializeComponent();
            quyenhan = phanquyen;
        }

        private void frmKhachHang_Load(object sender, EventArgs e)
        {
            btnRefresh_Click(sender, e);
                        
        }
        string quyenhan = "";
        Data data = new Data();
        MyDataPaging paging;
        string them = "";
        string sql;
        string lblNoiDungClick;
        string lblCellClick;        
        private void btnThem_Click(object sender, EventArgs e)
        {
            GridViewdata.ReadOnly = true;
            navigationPane1.Expanded = true;
            them = "them";
            btnThem.Enabled = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;
            txtTenKH.ReadOnly = false;            
            txtGhiChu.ReadOnly = false;            
            txtDiaChi.ReadOnly = false;
            txtDienThoai.ReadOnly = false;            
            cbGioiTinh.Enabled = true;
            GridViewdata.Enabled = false;
            //lbMaCongDan.Text = DateTime.Now.Day.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();

            txtMaKH.Focus();
            txtTenKH.Text = "";            
            txtGhiChu.Text = "";            
            txtDiaChi.Text = "";
            txtDienThoai.Text = "";                        
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            GridViewdata.ReadOnly = true;
            string makh = "";
            if (GridViewdata.SelectedRows.Count > 1)
            {
                if (MessageBoxEx.Show("Bạn có muốn xóa khách hàng đã được chọn không ?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    for (int i = 0; i < GridViewdata.SelectedRows.Count; i++)
                    {
                        try
                        {
                            makh = GridViewdata.Rows[GridViewdata.SelectedRows[i].Index].Cells["MaKH"].Value.ToString();
                            sql = "Delete From tblKhachHang Where MaKH= N'" + makh  + "'";
                            data.executeNonQuery(sql);

                        }
                        catch { }
                    }
                    paging.Refresh();
                    //btnRefresh_Click(sender, e);
                }
            }
            else if (MessageBoxEx.Show("Bạn có muốn xóa khách hàng '" + txtTenKH.Text + "' này không ?", "DELETE", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                try
                {
                    sql = "Delete From tblKhachHang Where MaKH= N'" + txtMaKH.Text + "'";
                    data.executeNonQuery(sql);
                    btnRefresh_Click(sender, e);
                }
                catch
                {
                    MessageBoxEx.Show("Khách hàng này không thể xóa !");
                }

            }
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            GridViewdata.ReadOnly = false;
            navigationPane1.Expanded = true;
            them = "sua";            
            btnThem.Enabled = false;
            btnXoa.Enabled = false;
            btnSua.Enabled = false;
            btnLuu.Enabled = true;            
            txtTenKH.ReadOnly = false;                        
            txtGhiChu.ReadOnly = false;            
            txtDiaChi.ReadOnly = false;
            txtDienThoai.ReadOnly = false;            
            cbGioiTinh.Enabled = true;
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            GridViewdata.ReadOnly = true;
            if (them == "them")
            {
                try
                {
                    if (txtMaKH.Text.Replace(" ", "") == "")
                    {
                        MessageBoxEx.Show("Nhập mã khách hàng !");
                        txtMaKH.Focus();
                    }
                    else if (txtTenKH.Text.Replace(" ", "") == "")
                    {
                        MessageBoxEx.Show("Nhập Tên khách hàng !");
                        txtTenKH.Focus();
                    }
                    else
                    {
                        sql = @"INSERT INTO tblKhachHang(MaKH,TenKH,GioiTinh,DienThoai,DiaChi, GhiChu)
                                VALUES(N'" + txtMaKH.Text + "',N'" + txtTenKH.Text + "',N'" + cbGioiTinh.Text + "',N'" + txtDienThoai.Text + "',N'" + txtDiaChi.Text + "',N'" + txtGhiChu.Text + "')";
                        try
                        {
                            data.executeNonQuery(sql);

                            btnRefresh_Click(sender, e);
                            btnLuu.Enabled = false;
                            btnThem_Click(sender, e);
                        }
                        catch {
                            MessageBox.Show("Mã khách hàng này đã có ! Vui lòng chọn mã khác.");
                            txtMaKH.Focus();
                        }
                    }


                }
                catch { }
            }
            if (them == "sua")
            {
                sql = "UPDATE tblKhachHang SET TenKH =N'" + txtTenKH.Text +
                            "',MaKH=N'" + txtMaKH.Text + 
                            "',GioiTinh=N'" + cbGioiTinh.Text + 
                            "',DiaChi=N'" + txtDiaChi.Text + 
                            "',DienThoai=N'" + txtDienThoai.Text +
                            "',GhiChu=N'" + txtGhiChu.Text + "' WHERE MaKH='" + txtMaKH.Text + "' ";
                data.executeNonQuery(sql);
                btnRefresh_Click(sender, e);
            }

            GridViewdata.Enabled = true;

        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            GridViewdata.ReadOnly = true;
            them = "";            
            btnThem.Enabled = true;
            btnXoa.Enabled = true;
            btnSua.Enabled = true;
            btnLuu.Enabled = false;
            txtTenKH.ReadOnly = true;            
            txtGhiChu.ReadOnly = true;            
            txtDiaChi.ReadOnly = true;
            txtDienThoai.ReadOnly = true;            
            cbGioiTinh.Enabled = false;
            GridViewdata.Enabled = true;
            if (quyenhan == "Chỉ Xem")
            {
                btnThem.Visible = false;
                btnXoa.Visible = false;
                btnSua.Visible = false;
                btnLuu.Visible = false;
            }
            else if (quyenhan == "Xem - Thêm - Chỉnh Sửa")
            {
                btnXoa.Visible = false;
            }                        

            
            data.autoComplete(txtDiaChi, "tblKhachHang", "DiaChi");
            data.autoComplete(txtDienThoai, "tblKhachHang", "DienThoai");

            sql = "SELECT * FROM tblKhachHang";
            paging = new MyDataPaging("tblKhachHang", sql, "", "TenKH", 50, GridViewdata, txtTrangHienTai, lbTongSoTrang);
            paging.Home();            
           // hienthimauGridview();

        }
        private void GridViewdata_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {

                txtMaKH.Text = GridViewdata.Rows[e.RowIndex].Cells["MaKH"].Value.ToString();
                txtTenKH.Text = GridViewdata.Rows[e.RowIndex].Cells["TenKH"].Value.ToString();                
                txtGhiChu.Text = GridViewdata.Rows[e.RowIndex].Cells["GhiChu"].Value.ToString();                
                txtDiaChi.Text = GridViewdata.Rows[e.RowIndex].Cells["DiaChi"].Value.ToString();
                txtDienThoai.Text = GridViewdata.Rows[e.RowIndex].Cells["DienThoai"].Value.ToString();                
                cbGioiTinh.Text = GridViewdata.Rows[e.RowIndex].Cells["GioiTinh"].Value.ToString();                                
            }
            catch { }
        }

        private void cbSoItemTrenTrang_SelectedIndexChanged(object sender, EventArgs e)
        {
            paging.Update(Int32.Parse(cbSoItemTrenTrang.Text));
            paging.Home();
        }

        private void cbSoItemTrenTrang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                paging.Update(Int32.Parse(cbSoItemTrenTrang.Text));
                paging.Home();
            }
        }

        private void bindingNavigatorMoveFirstItem_Click(object sender, EventArgs e)
        {
            paging.Home();
        }

        private void bindingNavigatorMovePreviousItem_Click(object sender, EventArgs e)
        {
            paging.Previous();
        }

        private void bindingNavigatorMoveNextItem_Click(object sender, EventArgs e)
        {
            paging.Next();
        }

        private void bindingNavigatorMoveLastItem_Click(object sender, EventArgs e)
        {
            paging.End();
        }
        private void txtHoTen_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                cbGioiTinh.Focus();
            }
        }
        private void cbGioiTinh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                txtDienThoai.Focus();
            }
            if (e.KeyCode == Keys.Up)
            {
                txtTenKH.Focus();
            }
        }
        private void txtGhiChu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                btnLuu.Focus();
            }
            if (e.KeyCode == Keys.Up)
            {
                txtDiaChi.Focus();
            }
        }
        private void GridViewdata_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3 || e.KeyCode == Keys.Control || e.KeyCode == Keys.F)
            {
                GridViewdata.ReadOnly = true;
                frmTimKiem frmTim = new frmTimKiem("tblKhachHang", lblCellClick, lblNoiDungClick);
                frmTim.passData = new frmTimKiem.PassData(GetFirstValue);
                frmTim.ShowDialog();
            }
            if (e.KeyCode == Keys.F10)
            {
                GridViewdata.ReadOnly = false;
                MessageBox.Show("Mở chức năng chỉnh sửa");
            }
        }

        public void GetFirstValue(String value)
        {
            paging.Update(value);
            paging.Home();
        }

        private void GridViewdata_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                lblCellClick = GridViewdata.Columns[e.ColumnIndex].DataPropertyName.ToString();
                lblNoiDungClick = GridViewdata.SelectedCells[0].Value.ToString();
            }
            catch { }
        }

        private void GridViewdata_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            GridViewdata_CellClick(sender, e);
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            btnThem_Click(sender, e);
        }

        private void btnRefesh_Click(object sender, EventArgs e)
        {
            btnRefresh_Click(sender, e);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            btnXoa_Click(sender, e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            btnLuu_Click(sender, e);
        }

        //------------- In Lý Lịch-------------------------------
        private void btnInLyLich_Click(object sender, EventArgs e)
        {
            //if (MessageBoxEx.Show("Bạn có muốn In Lý Lịch Của Công Dân  '" + txtHoTen.Text + "'  này không ?", "THÔNG BÁO", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
            //{
            System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
            pd.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd_PrintPage);
            pd.PrintController = new System.Drawing.Printing.StandardPrintController();
            try
            {
                pd.Print();
            }
            catch
            {
                MessageBox.Show("Không thể kết nối với máy in", "Lỗi");
            }
            //}
        }

        private void pd_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            DataTable dtViPhamHanhChinh;
            String thongbao = "";
            int dongmoi = 0;
            int x = 10, y = 10;
            Font printFont = new Font("Tahoma", 10, FontStyle.Regular);
            Font printFontBold = new Font("Tahoma", 9, FontStyle.Regular);
            Font Tieude = new Font("Tahoma", 10, FontStyle.Bold);
            Font BangLyLich = new Font("Tahoma", 14, FontStyle.Bold);
            Graphics g = ev.Graphics;
            g.DrawString("CƠ SỞ DIỆP ÁNH DƯƠNG", printFont, Brushes.Black, x + 50, y);
            g.DrawString("Địa chỉ:", printFont, Brushes.Black, x + 60, y + 20);

            

            //g.DrawString("BẢNG LÝ LỊCH", BangLyLich, Brushes.Black, x + 300, y + 80);
            //g.DrawString("Họ Tên: " + txtTenKH.Text + "", printFont, Brushes.Black, x + 30, y + 120);
            //g.DrawString("Ngày, tháng, năm sinh: " + txtNgaySinh.Text + "", printFont, Brushes.Black, x + 30, y + 140);
            //g.DrawString("Giới tính: " + cbGioiTinh.Text + "", printFont, Brushes.Black, x + 30, y + 160);
            //g.DrawString("Nguyên quán: " + txtDiaChi.Text + "", printFont, Brushes.Black, x + 30, y + 180);
            //g.DrawString("Nơi sinh: " + txtDienThoai.Text + "", printFont, Brushes.Black, x + 30, y + 200);
            //g.DrawString("Số CMND: " + txtCMND.Text + "", printFont, Brushes.Black, x + 30, y + 220);
            //g.DrawString("Dân tộc: " + txtDanToc.Text + "", printFont, Brushes.Black, x + 30, y + 240);
            //g.DrawString("Nơi đăng ký hộ khẩu thường trú: " + txtSoNha.Text + "", printFont, Brushes.Black, x + 30, y + 260);
            //g.DrawString("Trình độ học vấn: " + txtTrinhDoHocVan.Text + "", printFont, Brushes.Black, x + 30, y + 280);
            //g.DrawString("Tôn giáo: " + txtTonGiao.Text + "", printFont, Brushes.Black, x + 30, y + 300);
            //g.DrawString("Nghề nghiệp: " + txtNgheNghiep.Text + "", printFont, Brushes.Black, x + 30, y + 320);
            //g.DrawString("Ở đâu chuyển đến: " + txtODauDen.Text + "", printFont, Brushes.Black, x + 30, y + 340);
            //g.DrawString("Đến ngày: " + txtNgayDen.Text + "", printFont, Brushes.Black, x + 30, y + 360);
            //g.DrawString("Chuyển đi đâu: " + txtDiDau.Text + "", printFont, Brushes.Black, x + 30, y + 380);
            //g.DrawString("Đi ngày: " + txtNgayDi.Text + "", printFont, Brushes.Black, x + 30, y + 400);



            //// In vi pham hanh chinh
            //sql = "SELECT * FROM tblViPhamHanhChinh WHERE cMaCongDan=N'" + lbMaCongDan.Text + "'";
            //dtViPhamHanhChinh = data.executeQueryTable(sql);
            //string chuoi = "";

            //if (dtViPhamHanhChinh.Rows.Count == 0)
            //{

            //    thongbao = "Chưa có vi phạm.";
            //    g.DrawString("Tiền sự: " + thongbao + "", printFont, Brushes.Black, x + 30, y + 420);
            //}
            //else
            //{
            //    g.DrawString("Tiền sự:", printFont, Brushes.Black, x + 30, y + 420);
            //    for (int i = 0; i < dtViPhamHanhChinh.Rows.Count; i++)
            //    {
            //        chuoi = "     Ngày " + dtViPhamHanhChinh.Rows[i]["cNgayViPham"].ToString() + ", vi phạm " + dtViPhamHanhChinh.Rows[i]["cHanhVi"].ToString() + ", được " + dtViPhamHanhChinh.Rows[i]["cCoQuanXuLy"].ToString() + ", xử lý " + dtViPhamHanhChinh.Rows[i]["cHinhThucXuLy"].ToString() + "";
            //        int cat = 100;
            //        int temp = 0;
            //        bool isCat = false;
            //        if (chuoi.Length > cat)
            //        {
            //            for (int j = cat; j > 0; j--)
            //            {
            //                isCat = false;
            //                if (chuoi[j] == ' ')
            //                {
            //                    //in ra o day
            //                    String Out = chuoi.Substring(0, cat - temp);
            //                    //bo cua teo vo
            //                    g.DrawString(Out, printFont, Brushes.Black, x + 50, y + 440 + dongmoi);
            //                    dongmoi = dongmoi + 20;
            //                    if (chuoi.Length - (cat - temp) > 0)
            //                    {
            //                        chuoi = chuoi.Substring(cat - temp, chuoi.Length - (cat - temp));
            //                        if (chuoi.Length < cat)
            //                            break;
            //                        isCat = true;
            //                        j = cat;
            //                        temp = 0;
            //                    }
            //                }
            //                if (!isCat)
            //                    temp++;
            //            }
            //        }
            //        else
            //        {
            //            g.DrawString(chuoi, printFont, Brushes.Black, x + 50, y + 440 + dongmoi);
            //            dongmoi = dongmoi + 20;
            //        }
            //    }
            //}

           


        }
 
        private void btnXuatExcel_Click(object sender, EventArgs e)
        {
            //try
            //{
            SaveFileDialog save = new SaveFileDialog();
            save.Title = "Chọn nơi lưu trữ";
            save.Filter = "Excel 2003 (*xls)| *xls";
            save.ShowDialog();
            if (save.FileName != "")
            {
                ExcelCOM.Application exApp = new ExcelCOM.Application();
                ExcelCOM.Workbook exBook = exApp.Workbooks.Add(ExcelCOM.XlWBATemplate.xlWBATWorksheet);
                ExcelCOM.Worksheet exSheet = (ExcelCOM.Worksheet)exBook.Worksheets[1];
                exSheet.Name = "Sheet1";

                progressBar1.Visible = true;
                progressBar1.Maximum = GridViewdata.RowCount;
                for (int cot = 1; cot < GridViewdata.Columns.Count - 1; cot++)
                {
                    ExcelCOM.Range r = (ExcelCOM.Range)exSheet.Cells[1, cot];
                    r.ColumnWidth = 15;
                    r.Value2 = GridViewdata.Columns[cot].HeaderText.ToString();
                    for (int k = 0; k < GridViewdata.Rows.Count; k++)
                    {
                        ExcelCOM.Range r0d = (ExcelCOM.Range)exSheet.Cells[k + 2, cot];
                        r0d.Value2 = "'" + GridViewdata.Rows[k].Cells[cot].Value.ToString();
                        progressBar1.Value = k;
                    }

                }

                progressBar1.Visible = false;

                exApp.Visible = false;
                exBook.SaveAs(save.FileName, ExcelCOM.XlFileFormat.xlWorkbookNormal,
                    null, null, false, false,
                    ExcelCOM.XlSaveAsAccessMode.xlExclusive,
                    false, false, false, false, false);
                exBook.Close(false, false, false);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                exApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
            }
            //}
            //catch
            //{

            //}
        }
        private void GridViewdata_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //GridViewNhom.Rows[e.RowIndex].Cells["cMaDM"].Value.ToString();
            DataGridViewRow drSelected = GridViewdata.Rows[e.RowIndex];
            //if (GridViewdata.Columns[e.ColumnIndex].Name == "cHoTen")
            //{
            sql = "UPDATE tblCongDan SET cHoTen=N'" +
                drSelected.Cells["cHoTen"].Value.ToString() +
                "',cAp=N'" + drSelected.Cells["cAp"].Value.ToString() +
                "',cQHChuHo=N'" + drSelected.Cells["cQuanHeChuHo"].Value.ToString() +
                "',cGioiTinh=N'" + drSelected.Cells["cGioiTinh"].Value.ToString() +
                "',cNgaySinh=N'" + drSelected.Cells["cNgaySinh"].Value.ToString() +
                "',cNguyenQuan=N'" + drSelected.Cells["cNguyenQuan"].Value.ToString() +
                "',cNoiSinh=N'" + drSelected.Cells["cNoiSinh"].Value.ToString() +
                "',cSoCMND=N'" + drSelected.Cells["cSoCMND"].Value.ToString() +
                "',cDanToc=N'" + drSelected.Cells["cDanToc"].Value.ToString() +
                "',cSoNha=N'" + drSelected.Cells["cSoNha"].Value.ToString() +
                "',cTrinhDoHocVan= N'" + drSelected.Cells["cTrinhDo"].Value.ToString() +
                "',cTonGiao=N'" + drSelected.Cells["cTonGiao"].Value.ToString() +
                "',cNgheNghiep=N'" + drSelected.Cells["cNgheNghiep"].Value.ToString() +
                "',cSoHoKhau=N'" + drSelected.Cells["cSoHoKhau"].Value.ToString() +
                "',cSoSoHoKhau=N'" + drSelected.Cells["cSoSoHoKhau"].Value.ToString() +
                "',cODauDen=N'" + drSelected.Cells["cODauDen"].Value.ToString() +
                "',cNgayDen=N'" + drSelected.Cells["cNgayDen"].Value.ToString() +
                "',cDiDau=N'" + drSelected.Cells["cDiDau"].Value.ToString() +
                "',cNgayDi=N'" + drSelected.Cells["cNgayDi"].Value.ToString() +
                "',cChuyenDiCaHo=N'" + drSelected.Cells["cChuyenDiCaHo"].Value.ToString() +
                "',cGhiChu=N'" + drSelected.Cells["cGhiChu"].Value.ToString() +
                "', cChet=N'" + drSelected.Cells["Chet"].Value.ToString() +
                "' WHERE cMaCongDan='" + txtMaKH.Text + "' ";


            data.executeNonQuery(sql);
            //btnRefresh_Click(sender, e);
            //MessageBox.Show(lbMaCongDan.Text);
            //MessageBox.Show("Cập nhật");
        }
        private void GridViewdata_Sorted(object sender, EventArgs e)
        {
            //hienthimauGridview();
        }
        private void btnHuy_Click(object sender, EventArgs e)
        {
            navigationPane1.Expanded = false;
            btnThem.Enabled = true;
            btnXoa.Enabled = true;
            btnSua.Enabled = true;
            btnLuu.Enabled = false;
            GridViewdata.Enabled = true;
        }
        private void txtMaKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                txtTenKH.Focus();
            }            
        }
        private void txtDienThoai_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                txtDiaChi.Focus();
            }
            if (e.KeyCode == Keys.Up)
            {
                cbGioiTinh.Focus();
            }
        }
        private void txtDiaChi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
                txtGhiChu.Focus();
            }
            if (e.KeyCode == Keys.Up)
            {
                txtDienThoai.Focus();
            }
        }

       
       
    }
}
